import gradio as gr
import os
from chat_assistant import SimpleChatAssistant
from config import APP_CONFIG, UI_CONFIG, AVATAR_CONFIG

def load_css():
    """加载CSS样式文件"""
    css_file = "styles.css"
    if os.path.exists(css_file):
        with open(css_file, "r", encoding="utf-8") as f:
            return f.read()
    else:
        print(f"警告: CSS文件 {css_file} 不存在，使用默认样式")
        return ""

def create_interface():
    """创建Gradio界面"""
    assistant = SimpleChatAssistant()
    
    # 加载CSS样式
    custom_css = load_css()

    # 创建Gradio界面
    with gr.Blocks(
        title=APP_CONFIG["app_name"],
        css=custom_css,
        theme=gr.themes.Soft()
    ) as demo:
        
        # 标题区域
        with gr.Column(elem_classes="main-container"):
            gr.HTML(f"""
            <div class="title">{APP_CONFIG["app_title"]}</div>
            <div class="subtitle">{APP_CONFIG["app_subtitle"]}</div>
            """)
            
            # 聊天区域
            chatbot = gr.Chatbot(
                label=APP_CONFIG["chatbot_label"],
                height=UI_CONFIG["chatbot_height"],
                show_copy_button=True,
                show_share_button=True,
                avatar_images=(
                    AVATAR_CONFIG["user_avatar"],
                    AVATAR_CONFIG["ai_avatar"]
                ),
                elem_id="custom-chatbot"
            )
            
            # 输入区域和按钮在同一行
            with gr.Row(elem_classes="input-row"):
                # 输入框占据大部分空间
                msg = gr.Textbox(
                    label="",
                    placeholder="请输入您的问题...（按Enter发送）",
                    scale=4,
                    container=False,
                    max_lines=UI_CONFIG["input_lines"],
                    lines=UI_CONFIG["input_lines"]
                )
                
                # 按钮列 - 垂直排列
                with gr.Column(scale=1, min_width=120, elem_classes="button-column"):
                    send_btn = gr.Button(
                        "发送", 
                        variant="primary", 
                        size="sm",
                        elem_classes="send-button"
                    )
                    clear_btn = gr.Button(
                        "清空对话", 
                        size="sm",
                        elem_classes="clear-button"
                    )

        def respond(message, chat_history):
            """处理用户消息并返回AI回复"""
            if not message.strip():
                return "", chat_history
            
            # 获取AI回复
            bot_response = assistant.chat(message, chat_history)
            
            # 更新聊天历史
            chat_history.append((message, bot_response))
            
            return "", chat_history
        
        def clear_chat():
            """清空对话历史"""
            return []
        
        # 事件绑定
        msg.submit(respond, [msg, chatbot], [msg, chatbot])
        send_btn.click(respond, [msg, chatbot], [msg, chatbot])
        clear_btn.click(clear_chat, outputs=chatbot)
    
    return demo

def main():
    """主函数"""
    # 创建并启动界面
    demo = create_interface()
    demo.launch(
        server_name=UI_CONFIG["server_host"],
        server_port=UI_CONFIG["server_port"],
        share=UI_CONFIG["share_link"],
        favicon_path=None
    )

if __name__ == "__main__":
    main()